//生成token
const jwt = require("jsonwebtoken");
const { JWT_EXPIRED, TOKEN_SECRET_KEY, CODE_ERROR, CODE_SUCCESS } = require("../config");

//密码加密
const bcrypt = require("bcryptjs");

//引入mysql操作
const { queryOne, querySql } = require("../utils/query");
//生成唯一id
const uuid = require("uuid");

exports.register = (req, res) => {
  const userinfo = req.body;
  const sqlFindSameUsername = 'select * from user where username=?'
  queryOne(sqlFindSameUsername, userinfo.username).then(v => {
    if (v) {
      res.json({code:CODE_ERROR, msg:"该用户已存在"});
    } else {
      userinfo.password = bcrypt.hashSync(userinfo.password, 10);
      userinfo.id = uuid.v1();
      userinfo.createTime = Date.now()
      const sqlAddUser = "insert into user set ?";
      querySql(sqlAddUser, userinfo).then(v => {
        if (v.affectedRows == 1) {
          res.json({code:CODE_SUCCESS, msg:"注册成功",});
        }
      });
    }
  });
};

exports.login = (req, res) => {
  const userinfo = req.body;
  const sqlFindSameUsername = "select * from user where username=?";

  queryOne(sqlFindSameUsername, userinfo.username).then(
    v => {
      if (!v) {
        res.json({code:CODE_ERROR, msg:"用户名不存在"});
      } else {
        if (v.isDelete) {
          res.json({code:CODE_ERROR,msg: "该用户已被删除"});
        } else if (bcrypt.compareSync(userinfo.password, v.password)) {
          const user = { username: userinfo.username };
          const token = "Bearer " + jwt.sign(user, TOKEN_SECRET_KEY, { expiresIn: JWT_EXPIRED });
          res.json({code:CODE_SUCCESS, msg:"登录成功", data:token});
        } else {
          res.json({code:CODE_ERROR, msg:"密码错误"});
        }
      }
    },
    v => {
      throw new Error("查询错误");
    }
  );
};
exports.getUserInfo = (req, res) => {
  const user = req.user;
  const sqlFindSameUsername = "select * from user where username=?";
  queryOne(sqlFindSameUsername, user.username).then(v => {
    if (!v) {
      res.json({code:CODE_ERROR,msg: "请求个人信息失败"});
    } else {
      if (v.isDelete) {
        return res.json({code:CODE_ERROR,msg: "该用户已被删除"});
      }
      let sqlUserRoles = "select limits from roles  where role=?";
      querySql(sqlUserRoles, v.roles).then(v1 => {
        if (!v1) {
          res.json({code:CODE_ERROR,msg: "请求个人信息失败"});
        } else {
          v.routes = v1.reduce((pre, cur) => {
            pre = pre.concat(cur.limits.split("-"));
            return pre;
          }, []);
          res.json({code:CODE_SUCCESS,msg: "请求成功",data: v});
        }
      });
    }
  });
};

exports.deleteUser = async (req, res) => {
  const id = req.params.id;
  const publishTest = "update user set isDelete=1 where id=?";

  const v = await querySql(publishTest, id);
  if (v.affectedRows == 1) {
    res.json({code:CODE_SUCCESS,msg: "删除成功"});
  } else {
    res.json({code:CODE_ERROR, msg:"删除失败"});
  }
};
exports.getUserList = async (req, res) => {
  const getUserList = "select * from user where roles <> ? and isDelete<>1 order by createTime DESC";
  const v = await querySql(getUserList, "总管理员");
  if (Array.isArray(v)) {
    res.json({code:CODE_SUCCESS,msg: "请求成功", data:v});
  }else{
    res.json({code:CODE_ERROR,msg: "请求失败", data:v});
  }
};
exports.updateUserInfo = async (req, res) => {
  const userInfo = req.body
  if(userInfo.password){
    userinfo.password = bcrypt.hashSync(userinfo.password, 10);
  }
  const updateUserInfo = "update user set ? where id=?";
  const v = await querySql(updateUserInfo, [userInfo,userInfo.id]);
  if (v.affectedRows == 1) {
    res.json({code:CODE_SUCCESS,msg: "修改成功"});
  }else{
    res.json({code: CODE_ERROR,msg: "修改失败"});
  }
};
exports.updatePassword = async (req, res) => {
  const info = req.body
  // console.log(info);
  const findUserPass = 'select password from user where id=? and isDelete<>1'
  const v = await queryOne(findUserPass, [info.id]);
  if (v) {
    if(bcrypt.compareSync(info.oldPassword, v.password)){
      info.newPassword  = bcrypt.hashSync(info.newPassword, 10)
      const insertNewPassword = 'update user set password=? where id=?'
      const vPass = await querySql(insertNewPassword, [info.newPassword,info.id]);
      // console.log(vPass);
      if(vPass.affectedRows == 1){
        res.json({code: CODE_SUCCESS,msg: "修改成功"});
      }else{
        res.json({code: CODE_ERROR,msg: "修改失败"});
      }
    }else{
      res.json({code: CODE_ERROR,msg: "原密码错误"});
    }
  }else{
    res.json({code: CODE_ERROR,msg: "修改失败"});
  }
};
